from rest_framework import serializers
from rest_framework.fields import SerializerMethodField

from shopping.models import Classification,Commodity,CommodityImg,ShoppingCart,OrderGoods,Order,Payment


# 商品分类序列器
class ClassificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Classification
        # fields = '__all__'
        exclude = ["create_time", "update_time","is_delete"]


# 根据一级分类得到所有的子级分类   班级得学生的数据
class ClassificationSerializerSimple(serializers.ModelSerializer):
    # parent 得到 Classification的数据
    classification_set = ClassificationSerializer(many=True, read_only=True)
    class Meta:
        model = Classification
        fields = ["id", "classification_set","name"]



# 商品图片序列器
class CommodityImgSerializer(serializers.ModelSerializer):
    class Meta:
        model = CommodityImg
        fields = ["src"]

# 商品序列器
class CommoditySerializer(serializers.ModelSerializer):
    # 一级分类 二级分类  商品图片的地址
    classification1_name = serializers.CharField(read_only=True, source="classification1.name")
    classification2_name = serializers.CharField(read_only=True, source="classification2.name")
    commodityimg_set = CommodityImgSerializer(many=True, read_only=True)
    class Meta:
        model = Commodity
        exclude = ["create_time", "update_time","is_delete"]

        extra_kwargs = {
            "sales":{"read_only":True},
            "comments":{"read_only":True},
        }

# 购物车的序列号化器
class ShoppingCartSerializer(serializers.ModelSerializer):
    # 添加商品详情的展示  数据来源  ==》get_commodityDetail  方法查询得到
    commodityDetail = SerializerMethodField()
    class Meta:
        model = ShoppingCart
        fields = "__all__"


    def validate(self, attr):
        # attr = {number: 1, commodity: "7"}
        if attr["number"] <  0:
            raise  serializers.ValidationError("商品数量不能小于0")
        # attr["number"] 加入购物车的商品数量  和 商品的库存
        if attr["number"] > attr["commodity"].stock:
            raise serializers.ValidationError("商品数量不能超过库存")
        return attr

    # 固定参数  参数一定是当前操作的模型
    def get_commodityDetail(self,shoppingcart): # 吧当前的模型对象传入 购物车模型对象
        # 通过购物车模型的正向访问
        return CommoditySerializer(shoppingcart.commodity).data



# 订单的序列器
class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = "__all__"

        # extra_kwargs = {
        #     "order_id" :{"read_only":True},
        #     "total_count" :{"read_only":True},
        #     "total_amount" :{"read_only":True},
        #     "status" :{"read_only":True},
        #     "user" :{"read_only":True},
        # }
        # 设置只读
        read_only_fields = ["order_id","total_count","total_amount","status","user"]


# 支付凭证序列器
class PaymentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Payment
        fields = "__all__"